from rest_framework import serializers
from goods.models import SKU,GoodsCategory,SPU,SPUSpecification,SpecificationOption,SKUSpecification
from django.db import transaction

#0,sku 的规格,选项序列化器
class SpecificationSerializer(serializers.Serializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

#1,skus序列化器
class SKUSerializer(serializers.ModelSerializer):

    #1,重写spu,spu_id
    spu = serializers.StringRelatedField(read_only=True,label="spu名称")
    spu_id = serializers.IntegerField()

    #2,重写category,category_id
    category = serializers.StringRelatedField(read_only=True,label="category名称")
    category_id = serializers.IntegerField()

    #3,规格信息
    specs = SpecificationSerializer(read_only=True,many=True)

    class Meta:
        model = SKU
        fields = "__all__"

    #4,重写create方法,数据入库
    @transaction.atomic
    def create(self, validated_data):

        #0,设置保存点
        sid = transaction.savepoint()

        try:
            #1,创建sku对象,设置基本信息
            sku = SKU.objects.create(**validated_data)

            #2,获取规格信息,遍历入库
            specs = self.context["request"].data["specs"]
            for spec in specs:
                SKUSpecification.objects.create(sku_id=sku.id,spec_id=spec["spec_id"],option_id=spec["option_id"])
        except Exception as e:
            transaction.savepoint_rollback(sid)
            raise serializers.ValidationError("添加sku失败")
        else:
            #3,返回响应
            transaction.savepoint_commit(sid)
            return sku

    #5,重写update方法,更新specs信息
    @transaction.atomic
    def update(self, instance, validated_data):

        #0,设置保存点
        sid = transaction.savepoint()

        try:
            #1,修改基础信息
            SKU.objects.filter(id=instance.id).update(**validated_data)

            #2,删除原有规格
            [spec.delete() for spec in instance.specs.all()]

            #2,1 修改规格信息
            specs = self.context["request"].data["specs"]
            for spec in specs:
                SKUSpecification.objects.create(sku_id=instance.id, spec_id=spec["spec_id"], option_id=spec["option_id"])
        except Exception as e:
            transaction.savepoint_rollback(sid)
            raise serializers.ValidationError("添加sku失败")
        else:
            #3,返回响应
            transaction.savepoint_commit(sid)
            return instance

#2,sku 分类序列化器
class SKUCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ["id","name"]

#3,spu 简要信息序列化器
class SPUListSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = ["id","name"]

#4,spu specification 序列化器

#选项序列化器
class SpecificationOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ["id","value"]

#规则序列化器
class SPUSpecificationSerializer(serializers.ModelSerializer):

    options = SpecificationOptionSerializer(read_only=True,many=True)

    class Meta:
        model = SPUSpecification
        fields = "__all__"